<template>
  <el-dialog
    :title="isEdit ? '编辑小组' : '新增小组'"
    v-model="dialogVisible"
    width="500px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="小组编号" prop="id">
        <el-input v-model="form.id" :disabled="isEdit" placeholder="请输入小组编号" />
      </el-form-item>
      
      <el-form-item label="小组名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入小组名称" />
      </el-form-item>
      
      <el-form-item label="描述">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          placeholder="请输入小组描述"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="'active'"
          :inactive-value="'inactive'"
          active-text="正常"
          inactive-text="停用"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">
        {{ isEdit ? '保存' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { classService } from '../../services/class'
import { showSuccess, showError } from '../../utils/message'

const props = defineProps({
  classId: {
    type: String,
    required: true
  }
})

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)

const form = ref({
  id: '',
  name: '',
  description: '',
  status: 'active'
})

const rules = {
  id: [{ required: true, message: '请输入小组编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入小组名称', trigger: 'blur' }]
}

const open = (data = null) => {
  isEdit.value = !!data
  if (data) {
    form.value = { ...data }
  } else {
    form.value = {
      id: '',
      name: '',
      description: '',
      status: 'active'
    }
  }
  dialogVisible.value = true
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true

    const data = {
      ...form.value,
      class_id: props.classId
    }
    
    if (isEdit.value) {
      await classService.updateGroup(form.value.id, data)
      showSuccess('修改成功')
    } else {
      await classService.createGroup(data)
      showSuccess('创建成功')
    }
    
    dialogVisible.value = false
    emit('success')
    form.value = { id: '', name: '', description: '', status: 'active' }
  } catch (error) {
    showError(error?.message || '操作失败')
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
}

const emit = defineEmits(['success'])

defineExpose({
  open
})
</script>
